<!--
 * @Author: whq
 * @Date: 2023
 * @LastEditors: whq
 * @Description: 数字滚动组件
-->
<template>
    <div style="display: flex;">
        <div v-for="(item, index) in numberList" :key="index" style="display: flex;">
            <span v-if="isNaN(item)">{{ item }}</span>
            <div class="number" :style="{ ...props.numberStyle }" v-else>
                <span class="number-item" ref="numberItem" :data-number="item" :data-index="index">0123456879</span>
            </div>
        </div>
    </div>
</template>
  
<script setup>
import { ref, onMounted, computed, watch } from 'vue';

const numberItem = ref(null);
const props = defineProps({
    value: {
        type: String || Number,
        default: 0
    },
    numberStyle: {
        type: Object,
        default: {
            'width': '30px',
            'height': '30px',
            'font-size': '30px',
        }
    }
})

watch(() => {
    props.value
}, (newName, oldName) => {
    if (newName) {
        setNumberTransform();
    }
});
const numberList = computed(() => String(props.value).split(""))
// 设置每一位数字的偏移
const setNumberTransform = () => {
    let obj = {};
    Array.from(numberItem.value).forEach(c => {
        let key = c.dataset.index;
        let value = c.dataset.number;
        let init = 0;
        obj[key] = setInterval(() => {
            if (init < value * 10) {
                init += 1;
                c.style.transform = `translateY(-${init}%)`;
            } else {
                clearInterval(obj[key]);
                obj[key] = null;
            }
        }, 10);
    });
}
onMounted(() => {
    setNumberTransform()
})

</script>
<style scoped lang="scss">
.number {
    width: 20px;
    height: 20px;
    overflow: hidden;
    cursor: default;
    >span {
        writing-mode: vertical-rl;
        text-orientation: upright;
        transform: translateY(0%);
    }
}
</style>
  